import axios from 'axios'
import qs from 'qs'
import router from '../router'

axios.defaults.baseURL = 'http://localhost:8757/'
axios.interceptors.request.use(config => {
  config.headers.accessToken = window.sessionStorage.getItem('token')
  return config
})

export default {
  async downloadFile(url, timeout, path) {
    if (timeout === undefined || timeout === -1) {
      timeout = 10000
    }
    return await axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      timeout: timeout
    }).then(response => {
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob)
      const contentDisposition = response.headers['content-disposition']
      const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
      const result = patt.exec(contentDisposition)
      const filename = decodeURI(result[1])
      downloadElement.style.display = 'none'
      downloadElement.href = href
      downloadElement.download = filename
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement)
      window.URL.revokeObjectURL(href)
      return {
        code: '200',
        msg: '下载成功'
      }
    }).catch(() => {
      return {
        code: '-1',
        msg: '下载失败'
      }
    })
  },
  async upLoadByForm(url, form, timeout, path) {
    if (timeout === undefined || timeout === -1) {
      timeout = 10000
    }
    return await axios({
      method: 'post',
      timeout: timeout,
      url: url,
      data: form,
      headers: {
        'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
      }
    }).then(response => {
      this.checkResponse(response.data, path)
      return response.data
    }).catch(() => {
      return {
        code: '-1',
        msg: '请求失败'
      }
    })
  },
  async postByForm(url, form, timeout, path) {
    if (timeout === undefined || timeout === -1) {
      timeout = 10000
    }
    return await axios({
      method: 'post',
      timeout: timeout,
      url: url,
      data: form,
      transformRequest: [
        data => {
          return qs.stringify(data)
        }
      ]
    }).then(response => {
      this.checkResponse(response.data, path)
      return response.data
    }).catch(() => {
      return {
        code: '-1',
        msg: '请求失败'
      }
    })
  },
  async postByJson(url, json, timeout, path) {
    if (timeout === undefined || timeout === -1) {
      timeout = 10000
    }
    return await axios({
      method: 'post',
      timeout: timeout,
      url: url,
      data: json,
      headers: {
        'Content-Type': 'application/json'
      },
      transformRequest: [
        data => {
          return JSON.stringify(data)
        }
      ]
    }).then(response => {
      this.checkResponse(response.data, path)
      return response.data
    }).catch(() => {
      return {
        code: '-1',
        msg: '请求失败'
      }
    })
  },
  async get(url, params, timeout, path) {
    if (timeout === undefined || timeout === -1) {
      timeout = 10000
    }
    return await axios({
      method: 'get',
      url: url,
      params: params,
      timeout: timeout
    }).then(response => {
      this.checkResponse(response.data, path)
      return response.data
    }).catch(() => {
      return {
        code: '-1',
        msg: '请求失败'
      }
    })
  },
  async checkResponse(res, path) {
    if (res.msg === '身份异常') {
      window.sessionStorage.clear()
      if (path === undefined) {
        path = '/login'
      }
      if (router.path !== 'login') {
        await router.push(path)
      }
    }
  }
}
